/**
 * 时间管理控制器
 * 处理时间记录和活动分类相关的数据库操作
 */

import { BaseController, ensureDbInit, createResponse, createErrorResponse } from './BaseController'
import database from '../../utils/database'
import { generateId } from '../../mock/utils'

export class TimeController extends BaseController {
  constructor() {
    super('time_records')
  }
  
  /**
   * 获取时间记录列表
   */
  async getTimeRecords(params: {
    page?: number
    pageSize?: number
    activityId?: string
    startDate?: string
    endDate?: string
    status?: string
  } = {}) {
    try {
      const {
        page = 1,
        pageSize = 20,
        activityId,
        startDate,
        endDate,
        status
      } = params
      
      let whereClause = 'is_deleted = 0'
      let whereParams: any[] = []
      
      if (activityId) {
        whereClause += ' AND activity_id = ?'
        whereParams.push(activityId)
      }
      
      if (startDate) {
        whereClause += ' AND start_time >= ?'
        whereParams.push(startDate)
      }
      
      if (endDate) {
        whereClause += ' AND start_time <= ?'
        whereParams.push(endDate)
      }
      
      if (status) {
        whereClause += ' AND status = ?'
        whereParams.push(status)
      }
      
      return await this.getList({
        page,
        pageSize,
        where: whereClause,
        whereParams,
        orderBy: 'start_time DESC'
      })
    } catch (error: any) {
      return createErrorResponse(error.message || '获取时间记录失败')
    }
  }
  
  /**
   * 创建时间记录
   */
  async createTimeRecord(data: {
    activityId: string
    startTime: string
    endTime?: string
    duration?: number
    description?: string
    tags?: string[]
    status?: string
  }) {
    try {
      await ensureDbInit()
      const recordId = generateId()
      const now = new Date().toISOString()
      
      const recordData = {
        id: recordId,
        user_id: 'current_user',
        activity_id: data.activityId,
        start_time: data.startTime,
        end_time: data.endTime || null,
        duration: data.duration || 0,
        description: data.description || '',
        tags: JSON.stringify(data.tags || []),
        status: data.status || 'completed',
        created_at: now,
        updated_at: now,
        is_deleted: 0
      }
      
      await database.insert('time_records', recordData)
      
      return createResponse({
        id: recordId,
        ...data,
        createdAt: now,
        updatedAt: now
      })
    } catch (error: any) {
      return createErrorResponse(error.message || '创建时间记录失败')
    }
  }
  
  /**
   * 更新时间记录
   */
  async updateTimeRecord(id: string, data: any) {
    try {
      await ensureDbInit()
      const updateData = {
        ...data,
        updated_at: new Date().toISOString()
      }
      
      if (updateData.tags) {
        updateData.tags = JSON.stringify(updateData.tags)
      }
      
      const rowsAffected = await database.update(
        'time_records',
        updateData,
        'id = ? AND is_deleted = 0',
        [id]
      )
      
      if (rowsAffected === 0) {
        return createErrorResponse('时间记录不存在', 1003)
      }
      
      return createResponse({ success: true })
    } catch (error: any) {
      return createErrorResponse(error.message || '更新时间记录失败')
    }
  }
  
  /**
   * 删除时间记录
   */
  async deleteTimeRecord(id: string) {
    return await this.hardDelete(id)
  }
  
  /**
   * 获取时间记录详情
   */
  async getTimeRecordDetail(id: string) {
    return await this.getDetail(id)
  }
  
  /**
   * 开始计时器
   */
  async startTimer(data: {
    activityId: string
    description?: string
    tags?: string[]
  }) {
    try {
      await ensureDbInit()
      const timerId = generateId()
      const now = new Date().toISOString()
      
      // 先停止其他正在运行的计时器
      await database.update(
        'time_timers',
        { status: 'stopped', updated_at: now },
        'status = ? AND user_id = ?',
        ['running', 'current_user']
      )
      
      const timerData = {
        id: timerId,
        user_id: 'current_user',
        activity_id: data.activityId,
        start_time: now,
        description: data.description || '',
        tags: JSON.stringify(data.tags || []),
        status: 'running',
        elapsed_time: 0,
        created_at: now,
        updated_at: now
      }
      
      await database.insert('time_timers', timerData)
      
      return createResponse({
        id: timerId,
        ...data,
        startTime: now,
        status: 'running',
        elapsedTime: 0,
        createdAt: now,
        updatedAt: now
      })
    } catch (error: any) {
      return createErrorResponse(error.message || '启动计时器失败')
    }
  }
  
  /**
   * 停止计时器
   */
  async stopTimer(id: string) {
    try {
      await ensureDbInit()
      const now = new Date().toISOString()
      
      // 获取计时器信息
      const timerResult = await database.query(
        'SELECT * FROM time_timers WHERE id = ? AND status = ?',
        [id, 'running']
      )
      
      if (timerResult.code !== 0 || !timerResult.data || timerResult.data.length === 0) {
        return createErrorResponse('计时器不存在或已停止', 1003)
      }
      
      const timer = timerResult.data[0]
      const startTime = new Date(timer.start_time)
      const endTime = new Date(now)
      const duration = Math.floor((endTime.getTime() - startTime.getTime()) / 1000)
      
      // 更新计时器状态
      await database.update(
        'time_timers',
        {
          status: 'stopped',
          end_time: now,
          elapsed_time: duration,
          updated_at: now
        },
        'id = ?',
        [id]
      )
      
      // 创建时间记录
      const recordId = generateId()
      const recordData = {
        id: recordId,
        user_id: timer.user_id,
        activity_id: timer.activity_id,
        start_time: timer.start_time,
        end_time: now,
        duration: duration,
        description: timer.description,
        tags: timer.tags,
        status: 'completed',
        created_at: now,
        updated_at: now,
        is_deleted: 0
      }
      
      await database.insert('time_records', recordData)
      
      return createResponse({
        timerId: id,
        recordId: recordId,
        duration: duration,
        endTime: now
      })
    } catch (error: any) {
      return createErrorResponse(error.message || '停止计时器失败')
    }
  }
  
  /**
   * 暂停计时器
   */
  async pauseTimer(id: string) {
    try {
      await ensureDbInit()
      const now = new Date().toISOString()
      
      // 获取计时器信息
      const timerResult = await database.query(
        'SELECT * FROM time_timers WHERE id = ? AND status = ?',
        [id, 'running']
      )
      
      if (timerResult.code !== 0 || !timerResult.data || timerResult.data.length === 0) {
        return createErrorResponse('计时器不存在或未运行', 1003)
      }
      
      const timer = timerResult.data[0]
      const startTime = new Date(timer.start_time)
      const currentTime = new Date(now)
      const elapsedTime = timer.elapsed_time + Math.floor((currentTime.getTime() - startTime.getTime()) / 1000)
      
      // 更新计时器状态
      await database.update(
        'time_timers',
        {
          status: 'paused',
          elapsed_time: elapsedTime,
          updated_at: now
        },
        'id = ?',
        [id]
      )
      
      return createResponse({
        id: id,
        status: 'paused',
        elapsedTime: elapsedTime
      })
    } catch (error: any) {
      return createErrorResponse(error.message || '暂停计时器失败')
    }
  }
  
  /**
   * 恢复计时器
   */
  async resumeTimer(id: string) {
    try {
      await ensureDbInit()
      const now = new Date().toISOString()
      
      // 获取计时器信息
      const timerResult = await database.query(
        'SELECT * FROM time_timers WHERE id = ? AND status = ?',
        [id, 'paused']
      )
      
      if (timerResult.code !== 0 || !timerResult.data || timerResult.data.length === 0) {
        return createErrorResponse('计时器不存在或未暂停', 1003)
      }
      
      // 更新计时器状态
      await database.update(
        'time_timers',
        {
          status: 'running',
          start_time: now, // 重新设置开始时间
          updated_at: now
        },
        'id = ?',
        [id]
      )
      
      return createResponse({
        id: id,
        status: 'running',
        resumeTime: now
      })
    } catch (error: any) {
      return createErrorResponse(error.message || '恢复计时器失败')
    }
  }
  
  /**
   * 获取当前运行的计时器
   */
  async getCurrentTimer() {
    try {
      await ensureDbInit()
      const result = await database.query(
        'SELECT * FROM time_timers WHERE user_id = ? AND status IN (?, ?) ORDER BY updated_at DESC LIMIT 1',
        ['current_user', 'running', 'paused']
      )
      
      if (result.code !== 0) {
        return createErrorResponse(result.message || '获取当前计时器失败')
      }
      
      const data = result.data || []
      if (data.length === 0) {
        return createResponse(null)
      }
      
      const timer = data[0]
      let elapsedTime = timer.elapsed_time
      
      // 如果计时器正在运行，计算当前已用时间
      if (timer.status === 'running') {
        const startTime = new Date(timer.start_time)
        const currentTime = new Date()
        elapsedTime += Math.floor((currentTime.getTime() - startTime.getTime()) / 1000)
      }
      
      return createResponse({
        ...timer,
        elapsedTime,
        tags: timer.tags ? JSON.parse(timer.tags) : []
      })
    } catch (error: any) {
      return createErrorResponse(error.message || '获取当前计时器失败')
    }
  }
  
  /**
   * 获取活动分类列表
   */
  async getActivityCategories(params: {
    page?: number
    pageSize?: number
    isActive?: boolean
  } = {}) {
    try {
      const { page = 1, pageSize = 20, isActive } = params
      
      let whereClause = 'is_deleted = 0'
      let whereParams: any[] = []
      
      if (isActive !== undefined) {
        whereClause += ' AND is_active = ?'
        whereParams.push(isActive ? 1 : 0)
      }
      
      const result = await database.paginate('time_activity_categories', {
        page,
        pageSize,
        where: whereClause,
        whereParams,
        orderBy: 'sort_order ASC, created_at DESC'
      })
      
      if (result.code !== 0) {
        return createErrorResponse(result.message || '获取活动分类失败')
      }
      
      const paginationData = result.data || {}
      return createResponse({
        list: paginationData.list,
        page: paginationData.page,
        pageSize: paginationData.pageSize,
        total: paginationData.total
      })
  
    } catch (error: any) {
      return createErrorResponse(error.message || '获取活动分类失败')
    }
  }
  
  /**
   * 创建活动分类
   */
  async createActivityCategory(data: {
    name: string
    description?: string
    color?: string
    icon?: string
    sortOrder?: number
  }) {
    try {
      await ensureDbInit()
      const categoryId = generateId()
      const now = new Date().toISOString()
      
      const categoryData = {
        id: categoryId,
        user_id: 'current_user',
        name: data.name,
        description: data.description || '',
        color: data.color || '#3498db',
        icon: data.icon || '',
        sort_order: data.sortOrder || 0,
        is_active: 1,
        created_at: now,
        updated_at: now,
        is_deleted: 0
      }
      
      await database.insert('time_activity_categories', categoryData)
      
      return createResponse({
        id: categoryId,
        ...data,
        isActive: true,
        createdAt: now,
        updatedAt: now
      })
    } catch (error: any) {
      return createErrorResponse(error.message || '创建活动分类失败')
    }
  }
  
  /**
   * 更新活动分类
   */
  async updateActivityCategory(id: string, data: any) {
    try {
      await ensureDbInit()
      const updateData = {
        ...data,
        updated_at: new Date().toISOString()
      }
      
      const rowsAffected = await database.update(
        'time_activity_categories',
        updateData,
        'id = ? AND is_deleted = 0',
        [id]
      )
      
      if (rowsAffected === 0) {
        return createErrorResponse('活动分类不存在', 1003)
      }
      
      return createResponse({ success: true })
    } catch (error: any) {
      return createErrorResponse(error.message || '更新活动分类失败')
    }
  }
  
  /**
   * 删除活动分类
   */
  async deleteActivityCategory(id: string) {
    try {
      await ensureDbInit()
      
      // 检查是否有关联的时间记录
      const recordsResult = await database.query(
        'SELECT COUNT(*) as count FROM time_records WHERE activity_id = ? AND is_deleted = 0',
        [id]
      )
      
      if (recordsResult.code !== 0) {
        return createErrorResponse('检查关联记录失败')
      }
      
      const recordsData = recordsResult.data || []
      const recordCount = (recordsData[0] && typeof recordsData[0].count !== 'undefined') ? recordsData[0].count : 0
      
      if (recordCount > 0) {
        return createErrorResponse('该分类下存在时间记录，无法删除', 1004)
      }
      
      const rowsAffected = await database.delete('time_activity_categories', 'id = ?', [id])
      
      if (rowsAffected === 0) {
        return createErrorResponse('活动分类不存在', 1003)
      }
      
      return createResponse({ success: true })
    } catch (error: any) {
      return createErrorResponse(error.message || '删除活动分类失败')
    }
  }
  
  /**
   * 获取时间统计
   */
  async getTimeStats(params: {
    startDate?: string
    endDate?: string
    activityId?: string
    groupBy?: 'day' | 'week' | 'month'
  } = {}) {
    try {
      await ensureDbInit()
      const { startDate, endDate, activityId, groupBy = 'day' } = params
      
      let whereClause = 'is_deleted = 0 AND status = ?'
      let whereParams: any[] = ['completed']
      
      if (activityId) {
        whereClause += ' AND activity_id = ?'
        whereParams.push(activityId)
      }
      
      if (startDate) {
        whereClause += ' AND start_time >= ?'
        whereParams.push(startDate)
      }
      
      if (endDate) {
        whereClause += ' AND start_time <= ?'
        whereParams.push(endDate)
      }
      
      // 总时长统计
      const totalResult = await database.query(
        `SELECT COALESCE(SUM(duration), 0) as totalDuration, COUNT(*) as totalRecords FROM time_records WHERE ${whereClause}`,
        whereParams
      )
      
      if (totalResult.code !== 0) {
        return createErrorResponse(totalResult.message || '查询时间统计失败')
      }
      
      const totalData = totalResult.data || []
      const totalDuration = (totalData[0] && typeof totalData[0].totalDuration !== 'undefined') ? totalData[0].totalDuration : 0
      const totalRecords = (totalData[0] && typeof totalData[0].totalRecords !== 'undefined') ? totalData[0].totalRecords : 0
      
      // 按分组统计
      let dateFormat = '%Y-%m-%d'
      if (groupBy === 'week') {
        dateFormat = '%Y-%W'
      } else if (groupBy === 'month') {
        dateFormat = '%Y-%m'
      }
      
      const groupResult = await database.query(
        `SELECT 
          strftime('${dateFormat}', start_time) as period,
          SUM(duration) as duration,
          COUNT(*) as records
        FROM time_records 
        WHERE ${whereClause}
        GROUP BY strftime('${dateFormat}', start_time)
        ORDER BY period DESC`,
        whereParams
      )
      
      if (groupResult.code !== 0) {
        return createErrorResponse(groupResult.message || '查询分组统计失败')
      }
      
      return createResponse({
        totalDuration,
        totalRecords,
        averageDuration: totalRecords > 0 ? Math.round(totalDuration / totalRecords) : 0,
        groupedData: groupResult.data || []
      })
    } catch (error: any) {
      return createErrorResponse(error.message || '获取时间统计失败')
    }
  }
}

// 导出单例实例
export const timeController = new TimeController()